class_name TrailPathFindingFinder
extends Node2D

#region 属性
## 寻路者
@export var finder:PhysicsBody2D
@export var target_group:Array[String]
## 最大寻路距离，负数表示不做限制
@export var max_find_distance:float = -1
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
#endregion
#region 公共方法
## 得到finder的位置
func get_finder_position() -> Vector2:
	return finder.global_position
## 得到最终的移动方向，如果查找不到，会返回（0，0）
func get_final_dir() -> Vector2:
	var final_dir:Vector2 = Vector2.ZERO
	var targets = _get_all_target_by_group()
	targets = _filter_targets(targets)
	var final_positions = []
	for target in targets:
		var final_position = _get_final_postion(target)
		if final_position != null:
			final_positions.append(final_position)
	final_positions.sort_custom(func(a,b):
		return (a-get_finder_position()).length() < (b-get_finder_position()).length()
	)
	if final_positions.size() > 0:
		final_dir = (final_positions[0] - get_finder_position()).normalized()
	return final_dir
#endregion
#region 私有方法
func _get_all_target_by_group() -> Array[Node2D]:
	var targets:Array[Node2D] = []
	var tree:SceneTree = get_tree()
	for group in target_group:
		if tree.has_group(group):
			targets.append_array(tree.get_nodes_in_group(group))
	return targets
func _get_recorder_position(target:Node2D) -> Vector2:
	var recorder:TrailPathFindingRecorder = Utils.find_child_by_type(target,TrailPathFindingRecorder,-1)
	if recorder:
		return recorder.get_recorder_position()
	else:
		return recorder.global_position
func _filter_targets(targets:Array[Node2D]):
	if max_find_distance >= 0:
		targets = targets.filter(func(target:Node2D):
			var recorder:TrailPathFindingRecorder = Utils.find_child_by_type(target,TrailPathFindingRecorder,-1)
			if recorder:
				return (recorder.get_recorder_position() - get_finder_position()).length() <= max_find_distance
			else:
				return (target.global_position - get_finder_position()).length() <= max_find_distance
		)
	targets.sort_custom(func(a:Node2D,b:Node2D):
		var position_a = _get_recorder_position(a)
		var position_b = _get_recorder_position(b)
		return (position_a - get_finder_position()).length() < (position_b - get_finder_position()).length()
	)
func _get_final_postion(target:Node2D):
	var final_position = null
	var recorder:TrailPathFindingRecorder = Utils.find_child_by_type(target,TrailPathFindingRecorder,-1)
	if recorder:
		var records = recorder.get_records()
		records.reverse()
		for record in records:
			var res = finder.test_move(finder.transform,target.global_position - get_finder_position())
			if not res:
				final_position = recorder.get_recorder_position()
				break
	else:
		var res = finder.test_move(finder.transform,target.global_position - get_finder_position())
		if not res:
			final_position = target.global_position
	return final_position
#endregion
#region 生命周期函数
func _get_configuration_warnings() -> PackedStringArray:
	var warnings = []
	if not finder:
		warnings.append("finder不能为null")
	return warnings
#endregion
